<template>
    <!-- 收获地址 -->
    <van-contact-card type="edit" :name="`${address.name} ${address.region_text}`" :tel="address.tel" v-if="Object.getOwnPropertyNames(address).length > 0 && AddressCount === 0" @click="OnAddressSelect"  />
    <van-contact-card type="add" v-else-if="Object.getOwnPropertyNames(address).length <= 0 && AddressCount > 0" @click="OnAddressSelect"  />
    <van-contact-card type="add" v-else @click="AddressShow = true"  />

    <!-- 商品卡片 -->
    <van-card
        v-for="(item, key) in CartList"
        :thumb="item.product.thumb_text"
        :num="item.nums"
        @click-thumb="ToProductInfo(item.proid)"
        :key="key"
    >
        <template #title>
            <div class="title" @click="ToProductInfo(item.proid)">{{item.product.name}}</div>
        </template>

        <!-- 卡片的插槽部分 -->
        <template #desc v-if="item.attrs">
            <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
            <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
        </template>

        <template #desc v-else>
            <van-tag class="tag" type="danger">无规格数据</van-tag>
            <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
        </template>

        <template #price>
            <div class="price">单价：￥{{item.price}}</div>
            <div class="price">合计：￥{{item.total}}</div>
        </template>
    </van-card>

    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true" />

    <!-- 支付方式的选择器 -->
    <van-popup 
        v-model:show="PayShow"
        position="bottom"
        round
    >
        <van-picker
            title="选择支付方式"
            :columns="PayList"
            @cancel="PayShow = false"
            @confirm="OnPayConfirm"
        />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell
        :coupons="CouponList"
        :chosen-coupon="CouponActive"
        @click="CouponShow = true"
    />

    <!-- 优惠券列表 -->
    <van-popup
        v-model:show="CouponShow"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px;"
    >
        <van-coupon-list
            :coupons="CouponList"
            :disabled-coupons="NotCouponList"
            :chosen-coupon="CouponActive"
            :exchange-button-disabled="true"
            :show-exchange-bar="false"
            @change="OnCouponChange"
        />
    </van-popup>

    <!--订单备注 -->
    <van-field 
        v-model="remark"
        rows="2"
        autosize
        label="订单备注"
        type="textarea"
        maxlength="120"
        placeholder="请输入订单备注"
        show-word-limit
    />

    <!-- 添加收货地址 -->
    <van-popup 
        v-model:show="AddressShow"
        position="bottom"
        round
    >
        <van-address-edit 
            show-set-default
            :area-list="areaList"
            :area-columns-placeholder="['请选择', '请选择', '请选择']"
            :address-info="AddressInfo"
            @save="OnAddressAdd"
        />
    </van-popup>


    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="OnSubmit" />
</template>

<script setup>
// 引入地区数据
import { areaList } from '@vant/area-data';
import { isObject } from 'vant/lib/utils';
import { ref } from 'vue';
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const address = ref({});
const CartList = ref([]);
const AddressCount = ref(0);
const cartids = ref(proxy.$route.query.cartids ?? 0);

// 订单备注
const remark = ref('');

// 支付方式
const PayShow = ref(false);
const PayActive = ref({text: '余额支付', value: 'money'});
const PayList = ref([
    {text: '余额支付', value: 'money'},
    {text: '微信支付', value: 'wx'},
    {text: '支付宝支付', value: 'zfb'},
])

// 优惠券
const CouponList = ref([]);
const NotCouponList = ref([]);
const CouponShow = ref(false);
const CouponActive = ref(-1);

const AddressInfo = ref({});
const AddressShow = ref(false);

onBeforeMount(() =>
{
    GetCartData();
    GetAddressInfo();
    GetCouponData();
});

const GetCartData = async () =>
{

    // 获取缓存数据
    const cache = proxy.$cart.value.length > 0 ? proxy.$cart.value : null;

    if(cache && !cartids.value)
    {
        CartList.value = cache;

        return false;
    }

    const params = {
        cartids:cartids.value,
        busid:business.value.id
    }

    // const apiUrl = String(cartids.value).includes(',') ? '/cart/confirm' : '/cart/info';
    // const result = await proxy.$http.post(apiUrl,params);
    const result = await proxy.$http.post('/cart/confirm',params);

    if(result.code === 1)
    {
        CartList.value = result.data;

        // 把商品规格转换对象
        CartList.value.map(item => item.attrs = JSON.parse(item.attrs));
    }else{
        proxy.$fail(result.msg,() => proxy.$router.back());
    }
}

const OnSubmit = async () =>
{
    // 如果有购物车id，那就说明购物车购买，走购物车逻辑，否则就是立即购买
    if(cartids.value && proxy.$cart.value.length <= 0)
    {
        if(PayActive.value.value === 'money') {
            const params = {
            busid:business.value.id,// 用户id
            cartids:cartids.value,// 购物车id
            addrid:address.value.id,// 用户收货地址
            pay:PayActive.value.value,// 用户选择的支付方式
            remark:remark.value,// 订单备注
        }
        

        if(CouponActive.value !== -1)
        {
            // 这个是领取优惠券的记录id
            params.couponid = CouponList.value[CouponActive.value].id;
        }

        const result = await proxy.$http.post('/order/cart',params);

        if(result.code === 1){
            
            /**
             * 订单提交成功后，跳转到订单详情页面，传递订单ID作为查询参数
             * replace: true, // 替换当前路由，不会留下历史记录
             * replace的特点：
             * 1. 不会留下历史记录，不能返回上一页
             * 2. 不能使用浏览器的返回按钮返回上一页
             */
            proxy.$success(result.msg,() => proxy.$router.push({path:result.url,query:{orderid:result.data.orderid},replace:true}))
        }else {
            proxy.$fail(result.msg)
        }
        }
    }
    if(proxy.$cart.value.length > 0 && !cartids.value)
    {
        if(PayActive.value.value === 'money') {
            const params = {
                busid:business.value.id,
                proid:proxy.$cart.value[0].proid,
                addrid:address.value.id,// 用户收货地址
                pay:PayActive.value.value,// 用户选择的支付方式
                remark:remark.value ? remark.value : null,// 订单备注
                price:proxy.$cart.value[0].price,// 商品价格
                nums:proxy.$cart.value[0].nums,// 商品数量
                attrs:proxy.$cart.value[0].attrs.length > 0 ? JSON.stringify(proxy.$cart.value[0].attrs) : null,// 已选择商品属性
                type:proxy.$cart.value[0].type
            }

            if(CouponActive.value !== -1)
            {
                // 这个是领取优惠券的记录id
                params.couponid = CouponList.value[CouponActive.value].id;
            }

            const result = await proxy.$http.post('/order/buy',params);

            if(result.code === 1){
                proxy.$success(result.msg,() => proxy.$router.push({path:result.url,query:{orderid:result.data.orderid},replace:true}))
            }else {
                proxy.$fail(result.msg);
            }

        }
    }

}

// 在确认订单界面新增收货地址
const OnAddressAdd = () =>
{

}

// 获取收货地址
const GetAddressInfo = async () =>
{
    // 获取缓存里有没有数据
    let cache = Object.getOwnPropertyNames(proxy.$address.value).length > 0 ? proxy.$address.value : null;

    if(cache)
    {
        address.value = cache;

        return false;
    }

    const params = {
        busid:business.value.id
    }

    const result = await proxy.$http.post('/cart/address',params);

    if(result.code === 1)
    {
        const info = result.data;

        if(isObject(info))
        {
            address.value = {
                id:info.id,
                name:info.consignee,
                tel:info.mobile,
                region_text:info.region_text + info.address
            }
        }else{
            AddressCount.value = info ? info : 0;
        }
    }
}

const OnAddressSelect = () => proxy.$router.push({path:'/address',query:{action:'confirm'}});

const OnPayConfirm = ({selectedOptions}) =>
{

    PayActive.value = selectedOptions[0];

    PayShow.value = false;
}

const GetCouponData = async () =>
{
    const params = {
        busid:business.value.id
    }

    const result = await proxy.$http.post('/cart/coupon',params);

    if(result.code === 1)
    {
        for(let item of result.data.CouponList)
        {
            CouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }

        for(let item of result.data.NotCouponList)
        {
            NotCouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }
    }
}

const OnCouponChange = (index) =>
{
    CouponActive.value = index;

    CouponShow.value = false;

    if(CouponActive.value !== -1)
    {
        // 选中的优惠券
        let coupon = CouponList.value[index];

        // 商品的总价
        let amount = 0;

        // 先计算出未使用优惠券的总价
        CartList.value.map(item => amount += parseFloat(item.total));

        // 折扣率
        let rate = coupon?.rate ? coupon.rate : 1;

        // 使用优惠券后的总价
        let RatePrice = parseFloat(amount) * parseFloat(rate);

        // 优惠了多少钱
        let CouponPrice = (parseFloat(amount) - parseFloat(RatePrice)).toFixed(2);
        
        CouponList.value[index].value = parseFloat(CouponPrice) * 100;
    }
}

const total = computed(() =>
{
    let total = 0;

    CartList.value.map((item) => total += parseFloat(item.total));

    // 使用优惠券
    if(CouponActive.value !== -1)
    {
        let rate = CouponList.value[CouponActive.value].rate;

        total = (total * rate).toFixed(2);
    }

    return total * 100;
});
</script>

<style scoped>
    .van-card{
        background-color:#fff;
    }

    :deep(.van-card__bottom){
        position: relative;
    }

    :deep(.van-card__num){
        position: absolute;
        bottom: 0px;
        right: 5px;
    }

    .title{
        font-size:14px;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin-bottom: 5px;
    }

    .tag{
        margin-right:5px;
    }

    .price{
        font-size:12px;
        font-weight: bold;
    }

    /* 姓名只一行显示，超出隐藏 */
    :deep(.van-contact-card__title) div:first-child{
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
    }
</style>